package org.hepeng.workx.spring.security.web;

import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * @author he peng
 */
public abstract class AbstractRouteSecurityConfigAttributeLoader implements SecurityConfigAttributeLoader {

    private static final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();
    private RouteLocator routeLocator;

    public AbstractRouteSecurityConfigAttributeLoader(RouteLocator routeLocator) {
        Assert.notNull(routeLocator , "routeLocator must not be null");
        this.routeLocator = routeLocator;
    }

    @Override
    public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> loadConfigAttribute(HttpServletRequest request) {
        Route route = this.routeLocator.getMatchingRoute(URL_PATH_HELPER.getRequestUri(request));
        if (Objects.isNull(route)) {
            route = feignSelfAsRoute();
        }

        return loadConfigAttribute(route);
    }

    protected abstract Route feignSelfAsRoute();

    protected abstract LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> loadConfigAttribute(Route route);

}
